import getUserAgent from 'gdt-jsapi/getUserAgent';
import dd from 'gdt-jsapi';
import { navigateBack, eventCenter, getCurrentInstance } from '@tarojs/taro';
//回调类型
type condition = () => boolean;
type callback = () => void;
//定义函数类型变量
let condition1: condition;
let callback1: callback;
/**
 * 统一设置回调和
 * 添加钉钉back监听
 */
function setCallbackAndDDBackListener(condition: condition, callback: callback) {
  console.log('setCallbackAndDDBackListener', this);
  condition1 = condition;
  callback1 = callback;
  eventCenter.on(getCurrentInstance().router?.onShow as string, () => {
    //如果是钉钉环境，添加钉钉back按钮监听
    inDDEnvironment();
  });
  eventCenter.on(getCurrentInstance().router?.onHide as string, () => {
    //删除钉钉back监听
    removeDDBack();
  });
}

/**
 * 如果在钉钉环境要对返回按钮单独处理
 */
function inDDEnvironment() {
  try {
    getUserAgent().then(() => {
      ddBack();
    });
  } catch (error) {}
}

/**
 * 点击返回按钮
 */
function back() {
  if (condition1()) {
    navigateBack();
  } else {
    callback1();
  }
}

// 判断是否为安卓
function isAndroid() {
  const u = navigator.userAgent;
  if (u.indexOf('Android') > -1 || u.indexOf('Linux') > -1) {
    if (window.ShowFitness !== undefined) return true;
  }
  return false;
}

//钉钉监听事件
let off;
/**
 * 钉钉Back返回按钮处理
 */
function ddBack() {
  dd.ready(() => {
    // 设置左上角返回事件可控
    dd.setNavLeftText({
      control: true,
      message: '返回',
      text: '返回',
      android: isAndroid() ? true : false,
    }).then(() => {
      off = dd.on('back', function (e) {
        e.preventDefault();
        if (condition1()) {
          // 移除监听
          off();
          off = null;
          //执行back
          dd.goBack();
        } else {
          callback1();
        }
      });
    });
  });
}
//删除钉钉监听
function removeDDBack() {
  if (off) {
    off();
    off = null;
  }
}

export { setCallbackAndDDBackListener, back };
